package com.yxc.securitydemo1.utils;

import com.yxc.securitydemo1.dao.MenuMapper;
import com.yxc.securitydemo1.entity.Menu;
import com.yxc.securitydemo1.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

//查找访问当前url需要什么角色（权限）
@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Autowired
    MenuMapper menuMapper;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        String requestUrl=((FilterInvocation)object).getRequestUrl();//获取当前访问路径
        List<Menu> menus=menuMapper.getAllMenus(); //获取所有的权限，每个权限又包括多个角色
        for(Menu menu:menus){
            if(antPathMatcher.match(menu.getUrl(),requestUrl)){ //用户访问的URL与数据库中的权限匹配
                List<Role> roles=menu.getRoles(); //获取该权限对应的所有角色
                String[] roleArr=new String[roles.size()];//角色集合转化为数组
                for(int i=0;i<roles.size();i++){
                    roleArr[i]=roles.get(i).getName();
                }
                return SecurityConfig.createList(roleArr);//角色数组转换为Collection<ConfigAttribute>返回
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}